import { UserI } from "@/models/user";
import $api from "@/api/index";
import { SpecializationI, SpecializationTypeI } from "@/models/specialization";
import { APIPagination } from "@/models/common";
import { useCallback, useEffect, useState } from "react";
import { getUsers } from "@/api/users";

export async function getSpecialization(
  params?: URLSearchParams | null
): Promise<APIPagination<SpecializationI>> {
  const res = await $api.get("api/specialization/", {
    headers: {
      Timestamp: new Date().toISOString(),
    },
  });

  return res.data;
}

export function useSpecialization(
  params?: URLSearchParams | null
): [
  APIPagination<SpecializationI> | undefined,
  SpecializationI[] | undefined,
  boolean
] {
  const [isLoading, setLoading] = useState(false);
  const [data, setData] = useState<APIPagination<SpecializationI>>();

  const load = useCallback(async () => {
    // if (!params) return;
    setLoading(true);

    try {
      const r = await getSpecialization(params);
      setData(r);
    } catch (error) {
      console.log({ error });
    } finally {
      setLoading(false);
    }
  }, [params]);

  useEffect(() => {
    load();
  }, [load]);

  return [data, data?.results, isLoading];
}

export async function getSpecializationType(
  params?: URLSearchParams | null
): Promise<APIPagination<SpecializationTypeI>> {
  const res = await $api.get("api/specialization_type/", {
    headers: {
      Timestamp: new Date().toISOString(),
    },
  });

  return res.data;
}

export function useSpecializationType(
  params?: URLSearchParams | null
): [
  APIPagination<SpecializationI> | undefined,
  SpecializationI[] | undefined,
  boolean
] {
  const [isLoading, setLoading] = useState(false);
  const [data, setData] = useState<APIPagination<SpecializationI>>();

  const load = useCallback(async () => {
    // if (!params) return;
    setLoading(true);

    try {
      const r = await getSpecializationType(params);
      const arr: SpecializationI[] = [
        ...r.results.map((i) => {
          return {
            id: i.id,
            specialization: i.type
              ? `${i.specialization.specialization} ${i.type}`
              : i.specialization.specialization,
          };
        }),
      ];
      setData({
        ...r,
        results: arr,
      });
    } catch (error) {
      console.log({ error });
    } finally {
      setLoading(false);
    }
  }, [params]);

  useEffect(() => {
    load();
  }, [load]);

  return [data, data?.results, isLoading];
}
